$(function () {
    // 步骤计数器
    let stepCounter = 0;

    // 协议配置模板
    const protocolTemplates = {
        http: `
            <div class="http-form">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">请求方法</label>
                        <select class="form-select http-method">
                            <option>GET</option>
                            <option>POST</option>
                            <option>PUT</option>
                        </select>
                    </div>
                    <div class="col-md-9">
                        <label class="form-label">请求路径</label>
                        <input type="text" class="form-control http-path">
                    </div>
                </div>
            </div>
        `,
        thrift: `
            <div class="thrift-form">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">服务名称</label>
                        <input type="text" class="form-control thrift-service">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">方法名称</label>
                        <input type="text" class="form-control thrift-method">
                    </div>
                </div>
            </div>
        `,
        sql: `
            <div class="sql-form">
                <div class="row g-3">
                    <div class="col-12">
                        <label class="form-label">SQL 语句</label>
                        <textarea class="form-control sql-query" rows="3"></textarea>
                    </div>
                </div>
            </div>
        `
    };

    // 初始化拖拽排序
    $('#stepsContainer').sortable({
        handle: '.handle',
        animation: 150
    });

    // 添加步骤
    $('#btnAddStep').click(function () {
        const newStep = $('.step-card').clone().removeClass('d-none');
        const stepId = `step_${Date.now()}`;
        newStep.attr('data-step-id', stepId);

        // 初始化协议选择
        const protocolSelect = newStep.find('.protocol-select');
        protocolSelect.on('change', function () {
            const protocol = $(this).val();
            newStep.find('.protocol-configs').html(protocolTemplates[protocol]);
        });

        // 初始加载HTTP表单
        protocolSelect.trigger('change');

        // 删除步骤
        newStep.find('.btn-remove-step').click(function () {
            newStep.remove();
        });

        $('#stepsContainer').append(newStep);
    });

    // 保存用例
    $('#btnSave').click(function () {
        const caseData = {
            name: $('#caseName').val(),
            base_url: $('#baseProtocol').val(),
            steps: []
        };

        // 收集步骤数据
        $('.step-card').each(function () {
            const step = {
                protocol_type: $(this).find('.protocol-select').val(),
                config: {}
            };

            switch (step.protocol_type) {
                case 'http':
                    step.config = {
                        method: $(this).find('.http-method').val(),
                        path: $(this).find('.http-path').val()
                    };
                    break;
                case 'thrift':
                    step.config = {
                        service: $(this).find('.thrift-service').val(),
                        method: $(this).find('.thrift-method').val()
                    };
                    break;
                case 'sql':
                    step.config = {
                        query: $(this).find('.sql-query').val()
                    };
                    break;
            }

            caseData.steps.push(step);
        });

        // 发送到后端
        $.ajax({
            url: '/api/cases/',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(caseData),
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            },
            success: function (response) {
                toastr.success('保存成功');
                if (response.id) {
                    $('#caseId').text('ID: ' + response.id);
                }
            },
            error: function (xhr) {
                toastr.error('保存失败: ' + xhr.responseJSON?.detail);
            }
        });
    });

    // 获取Cookie辅助函数
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});

// 加载已有用例数据
function loadCaseData(caseId) {
    $.get(`/api/cases/${caseId}/`, function(response) {
        $('#caseTitle').text(response.name);
        $('#caseId').text('ID: ' + response.id);
        $('#caseName').val(response.name);
        $('#baseProtocol').val(response.base_url);

        // 加载步骤
        response.steps.forEach(step => {
            $('#btnAddStep').trigger('click');
            const lastStep = $('.step-card').last();
            lastStep.find('.protocol-select').val(step.protocol_type).trigger('change');

            // 填充协议数据
            Object.entries(step.config).forEach(([key, value]) => {
                lastStep.find(`.${step.protocol_type}-${key}`).val(value);
            });
        });
    });
}


function validateForm() {
    let isValid = true;

    // 验证用例名称
    if($('#caseName').val().trim() === '') {
        toastr.warning('请输入用例名称');
        isValid = false;
    }

    // 验证步骤
    $('.step-card').each(function(index) {
        const protocol = $(this).find('.protocol-select').val();
        const requiredFields = {
            http: ['.http-path'],
            thrift: ['.thrift-service', '.thrift-method'],
            sql: ['.sql-query']
        };

        requiredFields[protocol].forEach(selector => {
            if($(this).find(selector).val().trim() === '') {
                toastr.warning(`步骤 ${index + 1} 存在未填写的必填项`);
                isValid = false;
            }
        });
    });

    return isValid;
}

// 在保存时调用验证
$('#btnSave').click(function() {
    if(!validateForm()) return;
    // ...原有保存逻辑
});